/*\
]
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Client;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Message.RecipientType;

/**
 *
 * @author shimaa
 */
public class Email extends javax.swing.JFrame {

    /**
     * Creates new form Email
     */
    String mail;
    public Email(String mail) {
        initComponents();
        this.mail = mail;
        msgsent.setVisible(false);
        errorEmail.setVisible(false);
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panel3 = new java.awt.Panel();
        jPanel3 = new javax.swing.JPanel();
        send = new javax.swing.JButton();
        msgsent = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        to = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        subject = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        toUser = new javax.swing.JTextField();
        msgSub = new javax.swing.JTextField();
        jPanel6 = new javax.swing.JPanel();
        errorEmail = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        msgarea = new javax.swing.JEditorPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Mail");
        setMinimumSize(new java.awt.Dimension(500, 500));

        panel3.setMinimumSize(new java.awt.Dimension(116, 100));
        panel3.setName("panel1"); // NOI18N
        panel3.setLayout(new java.awt.BorderLayout());

        jPanel3.setBackground(new java.awt.Color(102, 5, 51));

        send.setBackground(new java.awt.Color(255, 255, 255));
        send.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        send.setForeground(new java.awt.Color(102, 5, 51));
        send.setText("Send Message");
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });
        jPanel3.add(send);

        msgsent.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        msgsent.setForeground(new java.awt.Color(255, 255, 255));
        msgsent.setText("Message Sent Successfully");
        jPanel3.add(msgsent);

        panel3.add(jPanel3, java.awt.BorderLayout.SOUTH);

        jPanel1.setBackground(new java.awt.Color(102, 5, 51));
        jPanel1.setLayout(new java.awt.GridLayout(3, 1));

        to.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        to.setForeground(new java.awt.Color(255, 255, 255));
        to.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        to.setText("To ");
        to.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jPanel1.add(to);
        jPanel1.add(jLabel1);

        subject.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        subject.setForeground(new java.awt.Color(255, 255, 255));
        subject.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        subject.setText("Subject ");
        jPanel1.add(subject);

        panel3.add(jPanel1, java.awt.BorderLayout.WEST);

        jPanel2.setBackground(new java.awt.Color(102, 5, 51));
        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel5.setBackground(new java.awt.Color(102, 5, 51));
        jPanel5.setLayout(new java.awt.BorderLayout());
        jPanel5.add(toUser, java.awt.BorderLayout.PAGE_START);
        jPanel5.add(msgSub, java.awt.BorderLayout.PAGE_END);

        jPanel2.add(jPanel5, java.awt.BorderLayout.CENTER);

        jPanel6.setBackground(new java.awt.Color(102, 5, 51));

        errorEmail.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 12)); // NOI18N
        errorEmail.setForeground(new java.awt.Color(220, 15, 15));
        errorEmail.setText("Email not Valid");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(errorEmail)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(errorEmail)
                .addContainerGap(33, Short.MAX_VALUE))
        );

        jPanel2.add(jPanel6, java.awt.BorderLayout.LINE_END);

        panel3.add(jPanel2, java.awt.BorderLayout.CENTER);

        msgarea.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        jScrollPane2.setViewportView(msgarea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(panel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(panel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(1, 1, 1)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 645, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendActionPerformed
         boolean isSent = true;
         if(!toUser.getText().equals(""))//email
         {
             String mymail=toUser.getText();
             String myPattern = "([\\w\\-\\.]+)@((\\[([0-9]{1,3}\\.){3}[0-9]{1,3}\\])|(([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))";
             Pattern p=Pattern.compile(myPattern);
             Matcher m=p.matcher(mymail);
             boolean matchFound=m.find();
                    if(!(matchFound))
                    {
                           errorEmail.setVisible(true);
                    }if(matchFound){
                        try {
                            errorEmail.setVisible(false);
                    // Recipient's email ID needs to be mentioned.
                       String to = toUser.getText();
                    // Sender's email ID needs to be mentioned
                       String from = mail;
                       System.out.println(mail);
                    // Assuming you are sending email from localhost
                       String host = "localhost";
                   // Get system properties
                       Properties properties = System.getProperties();
                   // Get the default Session object.
                       Session session = Session.getDefaultInstance(properties);
                       try{
                            // Create a default MimeMessage object.
                               MimeMessage message = new MimeMessage(session);
                           // Set From: header field of the header.
                               message.setFrom(new InternetAddress(from));
                           // Set To: header field of the header.
                               message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
                           // Set Subject: header field
                               message.setSubject(msgSub.getText());

                           // Now set the actual message
                               message.setText(msgarea.getText());
                           // Send message
                               Transport.send(message);

                               toUser.setText("");
                               msgSub.setText("");
                               msgarea.setText("");

                               System.out.println("Sent message successfully....");
                           }
                       catch (MessagingException mex) 
                       {
                           mex.printStackTrace();
                       }


                   } catch (Exception e)
                       {
                       // msgsent.setText("ERROR:" + e.getMessage());
                           isSent = false;
                       }

                       if(isSent == true)
                       {
                           msgsent.setVisible(true);
                       }

                   }
          }   
           else
           {
              errorEmail.setVisible(true);
           }
    }//GEN-LAST:event_sendActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Email.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Email.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Email.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Email.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //new Email().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel errorEmail;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField msgSub;
    private javax.swing.JEditorPane msgarea;
    private javax.swing.JLabel msgsent;
    private java.awt.Panel panel3;
    private javax.swing.JButton send;
    private javax.swing.JLabel subject;
    private javax.swing.JLabel to;
    private javax.swing.JTextField toUser;
    // End of variables declaration//GEN-END:variables
}
